import { injectable, inject } from 'inversify';
import { IMessageRepository } from './interfaces/IRepository';
import { Message } from '../../../domain/entities/message.entity';
import { DataSource, Repository } from 'typeorm';
import { TYPES } from '../../ioc/types';

@injectable()
export class MessageRepository implements IMessageRepository<Message> {
  private repository: Repository<Message>;

  constructor(@inject(TYPES.DataSource) private dataSource: DataSource) {
    this.repository = dataSource.getRepository(Message);
  }

  async save(entity: Message): Promise<Message> {
    return this.repository.save(entity);
  }

  async findById(id: string): Promise<Message | null> {
    return this.repository.findOneBy({ id });
  }

  async findBySessionId(sessionId: string): Promise<Message[]> {
    return this.repository.find({
      where: { sessionId },
      order: { timestamp: 'ASC' },
      take: 100 // 限制最近 100 条消息
    });
  }

  async findOne(options: any): Promise<Message | null> {
    return this.repository.findOne(options);
  }

  async find(options?: any): Promise<Message[]> {
    return this.repository.find(options || {});
  }

  async delete(id: string): Promise<void> {
    await this.repository.delete(id);
  }
}